import dayjs from 'dayjs'

// 飞猪详情轮询
let feizhuTimer: any = null
const feizhuDetailLoop = (resolve: Function, reject: Function, httpFn: Function, needRequired = false) => {
  const loop = async () => {
    try {
      const { status, closeMsg, extraDataJson, verifyFlag } = await httpFn()

      if (!needRequired && status === 0 && closeMsg) {
        clearTimeout(feizhuTimer)
        feizhuTimer = null
        resolve({ closeMsg })
      } else {
        if (verifyFlag === 1) {
          clearTimeout(feizhuTimer)
          feizhuTimer = null

          resolve({ verifyFlag })
        } else {
          if (Object.keys(extraDataJson).length > 0 && extraDataJson.verifyType) {
            clearTimeout(feizhuTimer)
            feizhuTimer = null

            // 需要验证
            if (extraDataJson.verifyType === 1) {
              // 验证有错误信息
              if (extraDataJson.errMsg) {
                resolve({ verifyType: extraDataJson.verifyType, errMsg: extraDataJson.errMsg, verifyPhone: extraDataJson.verifyPhone })
              } else {
                // 没有错误信息，继续轮询
                resolve({
                  verifyType: extraDataJson.verifyType,
                  verifyPhone: extraDataJson.verifyPhone,
                  loop: () => (feizhuTimer = setTimeout(loop, 2000)),
                })
              }
            } else {
              // 不需要验证
              resolve({ verifyType: extraDataJson.verifyType })
            }
          } else {
            feizhuTimer = setTimeout(loop, 2000)
          }
        }
      }
    } catch (error: any) {
      clearTimeout(feizhuTimer)
      feizhuTimer = null
      reject(error)
    }
  }

  loop()
}

const clearFeizhuTimer = () => {
  clearTimeout(feizhuTimer)
  feizhuTimer = null
}

const closeDialog = () => {
  let closeTimer: any = null

  const startTimer = (timer: number) => {
    const start = dayjs().valueOf()

    return new Promise<void>((resolve) => {
      const loop = () => {
        if (dayjs().valueOf() - start > timer) {
          if (closeTimer) {
            clearTimeout(closeTimer)
            closeTimer = null
          }
          resolve()
        } else {
          closeTimer = setTimeout(loop, timer)
        }
      }

      loop()
    })
  }

  const clearTimer = () => {
    if (closeTimer) {
      clearTimeout(closeTimer)
      closeTimer = null
    }
  }

  return {
    startTimer,
    clearTimer,
  }
}

export { feizhuDetailLoop, clearFeizhuTimer, closeDialog }
